package wangshuai.risk.service.impl;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import publics.model.Company;
import publics.model.News;
import publics.util.Page;
import wangshuai.risk.service.NewsService;

@Component("newsService")
public class NewsServiceImpl implements NewsService{
	private HibernateTemplate hibernateTemplate;
	
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	// 注入 hibernate模版
	@Resource(name = "hibernateTemplate")	
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
		System.out.println("hibernateTemplate injected in NewsServiceImpl!");
	}

	public boolean deleteNews(Integer newsId) {
		// TODO Auto-generated method stub
		return false;
	}

	@SuppressWarnings("unchecked")
	public Page findByPage(Page page) {//在此偷懒了，应该建立Dao层
		final String hql = "select new News(n.id as id, n.title as title, n.date as date) from News n order by n.date desc";
		// "select new News(id, title, date) from News n order by n.date desc"
		final Integer offset = page.getStart();
		final Integer pageSize = page.getLimit();
		List<News> list = this.getHibernateTemplate().executeFind(
				new HibernateCallback() {
					public Object doInHibernate(Session session) throws HibernateException ,SQLException {
						//执行hibernate分页查询
						List<News> result = session.createQuery(hql)
							.setFirstResult(offset)
							.setMaxResults(pageSize)
							.list();
						return result;
					}
				}
				);
		page.setRoot(list);
		return page;
	}

	public Object saveNews(News news) {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean updateNews(News news) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}
	/* (non-Javadoc)
	 * @see wangshuai.risk.service.NewsService#findById(java.lang.Integer)
	 */
	public News findById(Integer newsId) {
		return this.getHibernateTemplate().get(News.class, newsId);
	}
	
	

}
